package config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Druid配置类
 */
@Slf4j
public class DruidConfig {

    private static final DruidDataSource dataSource;

    static {
        // 从配置文件加载属性
        Properties properties = new Properties();
        InputStream inputStream = DruidConfig.class.getClassLoader().getResourceAsStream("db.properties");
        if (inputStream != null) {
            try {
                properties.load(inputStream);
            } catch (IOException e) {
                log.error("加载数据源配置时出现异常: {}", e.getMessage());
            }
        } else {
            log.error("未找到db.properties配置文件");
        }
        dataSource = new DruidDataSource();
        dataSource.setUrl(properties.getProperty("db.url"));
        dataSource.setUsername(properties.getProperty("db.username"));
        dataSource.setPassword(properties.getProperty("db.password"));
        dataSource.setDriverClassName(properties.getProperty("db.driver"));
        dataSource.setInitialSize(5);
        dataSource.setMinIdle(5);
        dataSource.setMaxActive(20);
        dataSource.setMaxWait(60000);
        dataSource.setTimeBetweenEvictionRunsMillis(600000);
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setValidationQuery("SELECT 1 FROM DUAL");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        dataSource.setPoolPreparedStatements(true);
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

}
